﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Jb.Common.Extensions;
using Jb.Domain;
using Jb.Web.ViewModels;
using Jb.Web.Utility;
using AutoMapper;
using Jb.Web.ViewModels.UtilityModels;
using Jb.Search;

namespace Jb.Web.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class SearchConfigController : BaseController
    {
        private JbEntities _Context = new JbEntities();

        public SearchConfigController()
        {
        }

        public SearchConfigController(UserViewModel currentUser)
            : base(currentUser)
        {
        }

        public ActionResult Index()
        {
            return View();
        }
        
        /// <summary>
        /// Deletes all products (if any) from Lucene Index and DB Index and after that Re-Indexes them
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SearchIndexStatus(int progressJobID)
        {

            //ProductIndexManager indexManager = new ProductIndexManager();
            //ReIndexResult result = indexManager.ReIndex();
            /////Reload the Index searcher, to immediately availabe by the index searcher.
            //ProductSearchManager.Reload();
            //ViewData[AppConstants.ViewDataKeys.SAVED] = result;
            return View();
        }

        /// <summary>
        /// Reindexes Resumes
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public String ReIndexResumes(int jobID)
        {
            IIndexer indexer = null;
            try
            {
                indexer = IndexerFactory.GetIndexer(typeof(Resume));
                ReIndexResult result = indexer.ReIndex(jobID);
                ///Reload Searcher
                ISearcher resumeSearcher = SearcherFactory.GetSearcher(typeof(Resume));
                resumeSearcher.Reload();
                return result.ToJSON();
            }
            catch (Exception ex)
            {
                indexer.CloseWriter();
                var jobStatus = _Context.ProcessStatuses.FirstOrDefault(P => P.ID == jobID);
                if (jobStatus != null)
                {
                    jobStatus.Status = QueueStatus.ERROR;
                    jobStatus.Message = ex.Message;
                    _Context.SaveChanges();
                }
                return new { Error = ex.Message }.ToJSON();
            }
            //return String.Empty;
        }

        /// <summary>
        /// Reindexes Jobs
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public String ReIndexJobs(int jobID)
        {
            IIndexer indexer = null;
            try
            {
                indexer = IndexerFactory.GetIndexer(typeof(Job));
                ReIndexResult result = indexer.ReIndex(jobID);
                ///Reload Searcher
                ISearcher jobSearcher = SearcherFactory.GetSearcher(typeof(Job));
                jobSearcher.Reload();
                return result.ToJSON();
            }
            catch (Exception ex)
            {
                indexer.CloseWriter();
                var jobStatus = _Context.ProcessStatuses.FirstOrDefault(P => P.ID == jobID);
                if (jobStatus != null)
                {
                    jobStatus.Status = QueueStatus.ERROR;
                    jobStatus.Message = ex.Message;
                    _Context.SaveChanges();
                }
                return new { Error = ex.Message }.ToJSON();
            }            
        }
        
        /// <summary>
        /// Enqueues a Progress Status object for an ReIndexing Operation
        /// </summary>
        /// <param name="reIndexType"></param>
        /// <returns></returns>
        [HttpGet]
        public String EnQueueJob(String reIndexType)
        {
            Jb.Domain.ProcessStatus process = new Domain.ProcessStatus();
            _Context.ProcessStatuses.AddObject(process);
            process.Status = QueueStatus.ENQUEUED;
            process.Completed = 0;
            process.EnquedOn = DateTime.Now;
            if (String.Compare(reIndexType, "R", true) == 0) ///Resume Re-Indexing Process
            {
                process.Total = (from P in _Context.Resumes
                                 where P.JobSeeker.IsActive
                                     && P.JobSeeker.HasProfileCompleted
                                     && P.IsDefault
                                 select P.ID).Count();
                process.TargetMethod = "ResumeIndexer.ReIndex";

            }
            else ///Job Re Indexing Process
            {
                process.Total = (from P in _Context.Jobs
                                 where P.Company.IsActive
                                     && P.IsActive
                                     && !P.IsDeleted
                                 select P.ID).Count();
                process.TargetMethod = "JobIndexer.ReIndex";
            }
            _Context.SaveChanges();

            return new
            {
                ID = process.ID,
                Total = process.Total,
                Completed = process.Completed,
                Status = process.Status
            }.ToJSON();
        }
    }
}


